package com.zhihuichongcheng.application.ui.im.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.view.View;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.easeui.EaseConstant;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.im.runtimepermissions.PermissionsManager;
import com.zhihuichongcheng.application.ui.im.fragment.ChatFragment;
import com.zhihuichongcheng.application.ui.im.fragment.ImChatFragment;


/**
 * chat activity，EaseChatFragment was used {@link #}
 */
public class ChatActivity extends BaseActivity {
    public static ChatActivity activityInstance;
    private ImChatFragment chatFragment;
    private String toChatUsername;
    private int chatType;
    private String mUserName;
    private UserBean mUser;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_chat);
        setSystemBarColor(R.color.activity_color);
        activityInstance = this;
        chatType = getIntent().getIntExtra(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        toChatUsername = getIntent().getExtras().getString("userId");
        mUserName = getIntent().getExtras().getString("username");
        if (chatType == EaseConstant.CHATTYPE_SINGLE) {
            spUtil.putInt("chatType", 1);
            initData();
            setImRight(R.drawable.ic_chat_user, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString("userId", toChatUsername);
                    startActivity(ImUserInfoActivity.class, bundle);
                }
            });
        } else {
            if (chatType == EaseConstant.CHATTYPE_GROUP) {
                spUtil.putInt("chatType", 2);
                EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
                if (group != null) {
                    setTitle(group.getGroupName() + "(" + group.getMembers().size() + ")");
                }
                setImRight(R.drawable.ic_chat_group_user, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putString("userId", toChatUsername);
//                        startActivity(ImGroupDetailActivity.class,bundle);
                        startActivityForResult(ImGroupDetailActivity.class, 0, bundle);
                    }
                });
            }
        }
        PackageManager pm = getPackageManager();
        boolean permissionRecord = (PackageManager.PERMISSION_GRANTED) == pm.checkPermission("android.permission.RECORD_AUDIO",
                "com.zhihuichongcheng.application");
        if (!permissionRecord) {
            hasPermissionInManifest(mContext, Manifest.permission.RECORD_AUDIO);
        }

        //use EaseChatFratFragment
        chatFragment = new ChatFragment();
        //pass parameters to chat fragment
        chatFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.container, chatFragment).commit();
    }

    private void initData() {
        UserBean bean = spUtil.getObject(toChatUsername, UserBean.class);
        if (bean != null) {
            setTitle(bean.getUserName());
        }

    }

    public void hasPermissionInManifest(Context context, String permissionName) {
        ActivityCompat.requestPermissions(this,
                new String[]{permissionName},
                0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
            if (group != null) {
                setTitle(group.getGroupName() + "(" + group.getMembers().size() + ")");
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // make sure only one chat activity is opened
        String username = intent.getStringExtra("userId");
        if (toChatUsername.equals(username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }

    @Override
    public void onBackPressed() {
        chatFragment.onBackPressed();
//        if (EasyUtils.isSingleActivity(this)) {
//            Intent intent = new Intent(this, MainActivity.class);
//            startActivity(intent);
//        }
    }

    public String getToChatUsername() {
        return toChatUsername;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (resultCode == Activity.RESULT_OK) {
                finish();
            }
        }
    }
}
